<?php
/*
Plugin Name: WP-Dribble
Plugin URI: http://mharis.net
Description: Add dribble updates to your blog posts, pages and sidebar.
Author: Muhammad Haris - <a href='http://twitter.com/mharis'>@mharis</a> on twitter
Version: 1.0.0
Author URI: http://mharis.net
*/

class WPDribble {
	var $pluginPath;
	var $pluginUrl;
	
	public function __construct()
	{
		// Set Plugin Path
		$this->pluginPath = dirname(__FILE__);
	
		// Set Plugin URL
		$this->pluginUrl = WP_PLUGIN_URL . '/wp-dribble';
		
		add_shortcode('dribble', array($this, 'shortcode'));
		
		// Add shortcode support for widgets
		add_filter('widget_text', 'do_shortcode');
	}
	
	public function getImages($user, $images = 3, $width = 50, $height = 50, $caption = true)
	{
		include 'DribbleAPI.php';
		
		$dribbleAPI = new DribbleAPI($user);
		$shots = $dribbleAPI->getPlayerShots($images);
		
		if($shots) {
			$html[] = '<ul class="wp-dribble">';
			
			foreach($shots as $shot) {
				$image = $shot->image_url; // url of the image
				$fileName = $shot->id . '.png'; // generating a filename image_id.png
				
				if (!file_exists($this->pluginPath . '/full-images/' . $fileName)) { // check if the full image exists
					$rawImage = wp_remote_get($image); // get the full image
					$newImagePath = $this->pluginPath  . '/full-images/' . $fileName;
					$fp = fopen($newImagePath, 'x');
					fwrite($fp, $rawImage['body']); // save the full image
					fclose($fp);
				}
				
				// generate thumbnail url
				$localImage = $this->pluginUrl . '/timthumb.php?src=' . strstr($this->pluginPath, 'wp-content') . '/full-images/' . $fileName . '&w=' . $width . '&h=' . $height . '&q=100';
				
				if($caption) { // if caption is true
					$captionHTML = '<p class="wp-dribble-caption">' . $shot->title . '</p>';
				}
				
				// combine shot url, title and thumbnail to add to the ul list
				$html[] = '<li class="wp-dribble-list"><a href="' . $shot->url . '" title="' . $shot->title . '"><img src="' . $localImage . '" alt="' . $shot->title . '" /></a>'.$captionHTML.'</li>';
			}
			
			$html[] = '</ul>';
			
			// return the list html
			return implode("\n", $html);
		}
	}
	
	public function shortcode($atts)
	{
		// extract the attributes into variables
		extract(shortcode_atts(array(
			'images' => 3,
			'width' => 50,
			'height' => 50,
			'caption' => true,
		), $atts));
		
		// pass the attributes to getImages function and render the images
		return $this->getImages($atts['user'], $images, $width, $height, $caption);
	}
}

function wp_dribble($user, $images = 3, $width = 50, $height = 50, $caption = true)
{
	$wpDribble = new WPDribble;
	echo $wpDribble->getImages($user, $images, $width, $height, $caption);
}

$wpDribble = new WPDribble;